<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2016-10-22
 * Time: 10:27
 */

namespace app\src\insurance\action;


use app\admin\controller\Insurance;
use app\src\account\enmu\AccountEnmu;
use app\src\accountScore\logic\AccountScoreLogic;
use app\src\base\helper\ValidateHelper;
use app\src\base\action\BaseAction;
use app\src\consumehistory\logic\ConsumeHistoryLogic;
use app\src\insurance\logic\InsuranceLogic;
use app\src\insurance\logic\InsuranceOrderInfoLogic;
use app\src\insurance\logic\InsuranceOrderLogic;
use app\src\insurance\logic\InsuranceApplyLogic;
use app\src\insurance\model\InsuranceOrder;
use app\src\powersystem\enum\AdminRoleEnum;
use app\src\powersystem\logic\AuthGroupAccessLogic;
use app\src\profit\action\ProfitAction;
use app\src\profit\enum\ProfitEnum;
use app\src\seller\emnu\SellerOrderStatusEmnu;
use app\src\seller\helper\OrderCodeHelper;
use think\Db;

class InsuranceAction extends BaseAction
{

    /*
     * 用户上传支付信息接口
     */
    public function payImg($id,$img_id){

        $apply = (new InsuranceApplyLogic())->getInfo(['id'=>$id,'status'=>0]);

        if(!empty($apply['info'])){
            $order = (new InsuranceOrderInfoLogic())->getInfo(['apply_id'=>$apply['info']['id']]);
            if(!empty($order['info'])){


                $entity=[
                    'pay_img'=>$img_id,
                ];
                $result=(new InsuranceOrderInfoLogic())->save(['apply_id'=>$id],$entity);
                return $this->success('success');
            }else{
                return $this->error('当前保险申请没有支付信息');
            }
        }else{
            return $this->error('当前保险申请不存在');
        }
    }

    /*
     * 前台获取已申请车险订单
     */
    public function UserList($uid,$apply_id=''){
        if($apply_id==''){
            $map=['ia.uid'=>$uid,'ia.status'=>0];
        }else{
            $map=['ia.uid'=>$uid,'ia.status'=>0,'ia.id'=>$apply_id];
        }
        $order='ia.update_time desc';
        $user_apply=(new InsuranceApplyLogic())->queryApplys($map,$order,false);
        if(!empty($user_apply)){
            $tem='';$list=[];
            foreach($user_apply['info'] as $v){
                $tem=$v;
                $status=0;
                $tem['apply_info']=empty($v['apply_info'])?json_decode('{"info":"null"}'):json_decode($v['apply_info']);
                $tem['pay_info']=empty($v['pay_info'])?json_decode('{"info":"null"}'):json_decode($v['pay_info']);
                if(empty($v['pay_info'])&&$v['apply_status']==0){
                    $status=1;//用户提交申请，后台未反馈
                }elseif(!empty($v['pay_info'])&&$v['apply_status']==0&&empty($v['pay_img'])){
                    $status=2;//后台已反馈，用户未上传支付信息
                }elseif(!empty($v['pay_img'])&&$v['apply_status']==0) {
                    $status=3;//用户上传支付信息 后台审核中
                }elseif($v['apply_status']==1){
                    $status=4;//订单已完成
                }elseif($v['apply_status']==2) {
                    $status=5;//订单未通过审核
                }else{
                    $status=6;//订单处于审核的其他状态
                }
                $tem['status_type']=$status;
                $tem['father_name']='财产保险';
                $list[]=$tem;
            }
        }else{
            $list='';
        }
        return $this->success($list);
    }



    /*
     * 改变申请状态
     * status 1通过，2不通过
     */
    public function option($admin_uid,$id,$status){
        //判断权限
        $this->checkPower($admin_uid);
        //判断前置条件,该订单必须在支付信息里有信息
        if($status==1){

            //判断是否有支付信息，并在支付信息里写入通过
            $pay=$this->checkPay($id);

            if(!$pay['status']) return $this->error($pay['info']);

            Db::startTrans();
            $order_sure=(new InsuranceOrderInfoLogic())->save(['apply_id'=>$id,'status'=>0],['order_status'=>'1']);

            //通过申请
            $entity=[
                'handle_uid'=>$admin_uid,
                'apply_status'=>$status,
                'update_time'=>time()
            ];
            $result=(new InsuranceApplyLogic())->save(['id'=>$id],$entity);
            if($result['status']&&$order_sure['status']){
                //若为通过，则生成订单
                $order=$this->createapplyorder($id);
                $apply = (new InsuranceApplyLogic())->getInfo(['id'=>$id]);
                if($order['status']){
                    //订单生成之后，完成支付信息和购买凭证
                    $order_info=(new InsuranceOrderInfoLogic())->save(['apply_id'=>$id,'status'=>0],['order_id'=>$order['info']['order_id']]);
                    $consume=$this->consume_history($id,$order['info']['amount'],$order['info']['order_id']);
                    //$add_money=$this->addMoney($apply['info']['uid']);
                    $add_money['status']= true;
                    $insurance_order = (new InsuranceOrderInfoLogic())->getInfo(['apply_id'=>$id]);
                    $insurance_apply = (new InsuranceApplyLogic())->getInfo(['id'=>$id]);
                    $profit_deal = (new ProfitAction())->dealProfit(ProfitEnum::INSURANCE_TYPE,$insurance_apply['info']['uid'],'0',$order['info']['order_id']);
                    if($order_info&&$consume&&$add_money['status']&&$profit_deal['status']){
                        Db::commit();
                        return $this->success('success');
                    }
                    return $this->error('后续处理有错');
                }else{
                    Db::rollback();
                    return $this->error('order'.$order['info']);
                }
            }else{
                Db::rollback();
                return $this->error($result['info']);
            }
        }else{
            //若为不通过
            //apply order_info
            $apply=(new InsuranceApplyLogic())->saveByID($id,['apply_status'=>'2','update_time'=>NOW_TIME]);
            $order_info = (new InsuranceOrderInfoLogic())->getInfo(['apply_id'=>$id,'status'=>'0']);
            if(!empty($order_info['info'])){
                (new InsuranceOrderInfoLogic())->save(['apply_id'=>$id,'status'=>'0'],['order_status'=>2]);
            }


            return $this->success('success');

        }
    }
    /*
     * 完成购买保险，增加用户的提现积分
     */
    public function addMoney($uid){
        $type=AccountEnmu::USER;
        $amount=10000;
        $score_type=AccountScoreLogic::SCORE_TYPE_1;
        $reason='购买车险增加积分';
        $add_money=(new AccountScoreLogic())->plusScore($type,$uid,$score_type,$amount,$reason);
        return $add_money;
    }

    /*
     * 完成购买后，写入购买记录表
     */
    public function consume_history($apply_id,$price,$order_id){
        $apply=(new InsuranceApplyLogic())->getInfo(['id'=>$apply_id,'status'=>'0']);
        $order_info=(new InsuranceOrderInfoLogic())->getInfo(['apply_id'=>$apply_id,'status'=>'0']);

        if(!empty($apply['info'])&&!empty($order_info['info'])){

            $uid=$apply['info']['uid'];
            $snapshot=[
                'apply_info'=>$apply['info']['apply_info'],
                'pay_info'=>$order_info['info']['pay_info'],
            ];
            $entity=[
                'uid'=>$uid,
                'type'=>'1',
                'item_id'=>$order_id,
                'price'=>$price,
                'snapshot'=>json_encode($snapshot),
                'create_time'=>NOW_TIME,
                'status'=>'0'
            ];
            $consume_history=(new ConsumeHistoryLogic())->add($entity,'');
            if($consume_history['status']) return true;
            return false;
        }

    }

    /*
     * 判断保险申请是否已有支付信息
     */
    public function checkPay($apply_id){
        $apply_pay=(new InsuranceOrderInfoLogic())->getInfo(['apply_id'=>$apply_id]);
        if($apply_pay['status']){
            if(!empty($apply_pay['info'])){

                if(!empty($apply_pay['info']['pay_img'])) return $this->success('支付成功');
                return $this->error('没有支付截图');

            }else{
                return  $this->error('缺少车险订单支付信息,miss_apply_order');
            }
        }else{
            return  $this->error('查询出错,error_apply_order');
        }
    }


    /*
     * 判断后台用户是否有此权限
     */
    public function checkPower($uid){
        $map['uid']=$uid;
        $access_ids=$this->getAdminauthaccess();

        $map['group_id']=['in',$access_ids];
        $access=(new AuthGroupAccessLogic())->getInfo($map);
        if(!empty($access['info'])){
            return true;
        }else{
            return $this->error('您操作的用户不存在');
        }
    }


    /*
     * 获取管理员身份的access序号
     */
    public function getAdminauthaccess() {
        $ids    = [];
        $ids[] = AdminRoleEnum::getRoleIDBy(AdminRoleEnum::ROLE_Admin);
        $ids[] = AdminRoleEnum::getRoleIDBy(AdminRoleEnum::ROLE_Option);
        $ids[] = AdminRoleEnum::getRoleIDBy(AdminRoleEnum::ROLE_Service);
        return $ids;

    }

    /*
     * 生成车险订单
     */
    public function createapplyorder($id){
        //根据id查询已在数据库里的信息
        $apply=(new InsuranceApplyLogic())->getInfo(['id'=>$id]);
        $uid=$apply['info']['uid'];
        $insurance_order=(new InsuranceOrderInfoLogic())->getInfo(['apply_id'=>$id]);
        $pay_info=$insurance_order['info']['pay_info'];
        $pay_info=json_decode($pay_info,true);

        $amount=$pay_info['price'];
        $data = [
            'uid' => $uid,
            'apply_id'=>$id,
            'price' => $amount,
            'insurance_id' => $apply['info']['insurance_id'],
            'create_time' => NOW_TIME,
            //'order_status' => SellerOrderStatusEmnu::PAY,
            'order_code' => '',
            'status'=>0,
        ];

        $result = (new InsuranceOrderLogic())->add($data);
        if($result['status']){
            $id = $result['info'];
            (new InsuranceOrderLogic())->saveByID($id, ['order_code' => OrderCodeHelper::create(OrderCodeHelper::INSURANCE_ORDER, $id)]);
            return(['status'=>true,'info'=>['order_id'=>$id,'amount'=>$amount]]);
        }else{
            return(['status'=>false,'info'=>'订单添加未成功']);
        }
    }


}